package cn.yuanqiao.archive.qzj.service.impl;

import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.qzj.domain.YqdaQzjFile;
import cn.yuanqiao.archive.qzj.mapper.YqdaQzjFileMapper;
import cn.yuanqiao.archive.qzj.service.YqdaQzjFileService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class YqdaQzjFileServiceImpl implements YqdaQzjFileService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private YqdaQzjFileMapper yqdaQzjFileMapper;
    @Autowired
    private ITenantSysConfigService configService;

    @Override
    public List<YqdaQzjFile> selectList(Long qzjId) {
        return yqdaQzjFileMapper.selectList(qzjId);
    }

    @Override
    public int insertYqdaQzjFile(MultipartFile multipartFile, Long qzjId) {

        String qzjPath = configService.selectConfigByKey("QZJ_PATH");
        if(StringUtils.isEmpty(qzjPath)){
            throw new ServiceException("缺少系统参数QZJ_PATH");
        }
        File file = new File(qzjPath);
        if(!file.exists()){
            file.mkdirs();
        }
        String fileName = multipartFile.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
        String filePath = file.getAbsolutePath() +File.separator+ new Date().getTime() + "." + fileType;
        try {
            multipartFile.transferTo(new File(filePath));
        }catch (IOException e){
            logger.error(e.getMessage(),e);
            throw new ServiceException("文件保存失败!"+e.getMessage());
        }
        /*if(qzjId==123456){

        }*/
        YqdaQzjFile yqdaQzjFile = new YqdaQzjFile();
        yqdaQzjFile.setId(SnowflakeIdGenerator.generateId());
        yqdaQzjFile.setFileName(fileName);
        yqdaQzjFile.setFilePath(filePath);
        yqdaQzjFile.setFileType(fileType);
        yqdaQzjFile.setQzjId(qzjId);
        yqdaQzjFile.setIsDel(0);
        yqdaQzjFile.setTenantCode(SecurityUtils.getTenantCode());
        return yqdaQzjFileMapper.insertYqdaQzjFile(yqdaQzjFile);
    }

    @Override
    public YqdaQzjFile getById(Long id) {
        return yqdaQzjFileMapper.getById(id);
    }

    @Override
    public int delYqdaQzjFile(Long[] ids) {
        return yqdaQzjFileMapper.delYqdaQzjFile(ids);
    }
}
